/*
 * interrupt.c
 *
 *  Created on: 14/mar/2014
 *      Author: Mario
 */

#include "interruption.h"

/**
  * @brief  define a GPIO pin as source of interrupts.
  * @param  EXTI_PortSourceGPIOx : selects the GPIO port to be used as source for
  *          EXTI lines where x can be (A..I).
  * @param  EXTI_PinSourcex: specifies the EXTI line to be configured.
  *           This parameter can be EXTI_PinSourcex where x can be (0..15, except
  *           for EXTI_PortSourceGPIOI x can be (0..11).
  * @param  EXTI_Line: Specifies the EXTI Line to be configured.
  *     This parameter can be EXTI_LINEx where x can be (0..15)
  * @param  EXTI_Trigger: Specify whether Interrupt is generated on the rising, falling or rising and falling edges
  * @param  Priority: Priority of the Interrupt (lower the number the higher the priority)
  * @retval None
  * @NOTE: Note that there are 22 EXTI interrupt sources. This function can only be used to configure upto
  *     15 of those interrupts sources
  */
void Attach_GPIO_Interrupt(uint8_t EXTI_PortSourceGPIOx, uint8_t EXTI_PinSourcex, uint32_t EXTI_Line,
  EXTITrigger_TypeDef EXTI_Trigger, uint8_t Priority)
{
 uint8_t EXTI_IRQn = 0;
 switch (EXTI_Line)
 {
 case 0x1:
  EXTI_IRQn = EXTI0_IRQn;
  break;
 case 0x2:
  EXTI_IRQn = EXTI1_IRQn;
  break;
 case 0x4:
  EXTI_IRQn = EXTI2_IRQn;
  break;
 case 0x8:
  EXTI_IRQn = EXTI3_IRQn;
  break;
 case 0x10:
  EXTI_IRQn = EXTI4_IRQn;
  break;
 case 0x20: case 0x40: case 0x80: case 0x100: case 0x200:
  EXTI_IRQn = EXTI9_5_IRQn;
  break;
 case 0x400: case 0x800: case 0x1000: case 0x2000: case 0x4000: case 0x8000:
  EXTI_IRQn = EXTI15_10_IRQn;
  break;
 }

 /* Connect EXTI Line to appropriate GPIO Pin */
 RCC_APB2PeriphClockCmd(RCC_APB2Periph_SYSCFG, ENABLE);
 SYSCFG_EXTILineConfig(EXTI_PortSourceGPIOx, EXTI_PinSourcex);

 NVIC_InitTypeDef   NVIC_InitStructure;
 EXTI_InitTypeDef   EXTI_InitStructure;

 /* Configure EXTI Line */
 EXTI_InitStructure.EXTI_Line = EXTI_Line;
 EXTI_InitStructure.EXTI_Mode = EXTI_Mode_Interrupt;
 EXTI_InitStructure.EXTI_Trigger = EXTI_Trigger;
 EXTI_InitStructure.EXTI_LineCmd = ENABLE;
 EXTI_Init(&EXTI_InitStructure);

 /* Enable and set EXTI Line Interrupt */
 NVIC_InitStructure.NVIC_IRQChannel = EXTI_IRQn;
 NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = Priority;
 NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0x01;
 NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
 NVIC_Init(&NVIC_InitStructure);
}
